package com.wlw.eye.adapter

import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.flexbox.FlexboxLayoutManager
import com.wlw.eye.R
import com.wlw.eye.ui.ResultActivity
import kotlinx.android.synthetic.main.item_search.view.*

class SearchAdapter(list: ArrayList<String>) : RecyclerView.Adapter<BaseHolder>() {
    var list: ArrayList<String>? = null
    var mDialogListener: OnDialogDissmiss? = null

    init {
        this.list = list
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseHolder {
        return BaseHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_search, parent, false))
    }

    override fun getItemCount(): Int = list?.size ?: 0

    override fun onBindViewHolder(holder: BaseHolder, position: Int) {
        onBindView(holder.itemView, list?.get(position))
    }

    private fun onBindView(itemView: View?, str: String?) {
        itemView?.tv_title?.text = str
        val params = itemView?.layoutParams
        if (params is FlexboxLayoutManager.LayoutParams)
            params.flexGrow = 1.0f
        itemView?.setOnClickListener {
            val keyWord = str
            val intent = Intent(itemView.context, ResultActivity::class.java)
            intent.putExtra("keyWord", keyWord)
            itemView.context.startActivity(intent)

            mDialogListener?.onDismiss()
        }
    }

    fun setOndialogDismissListener(onDialogDissmiss: OnDialogDissmiss) {
        mDialogListener = onDialogDissmiss
    }

    interface OnDialogDissmiss {
        fun onDismiss()
    }
}